package com.hand.todo.app.service.impl;

import com.hand.todo.app.service.SoLineService;
import com.hand.todo.domain.entity.HodrSoHeader;
import com.hand.todo.domain.entity.HodrSoLine;
import com.hand.todo.domain.repository.SoHeaderRepository;
import com.hand.todo.domain.repository.SoLineRepository;
import com.hand.todo.infra.mapper.SoLineMapper;
import io.choerodon.core.domain.Page;
import io.choerodon.core.exception.CommonException;
import io.choerodon.mybatis.pagehelper.PageHelper;
import io.choerodon.mybatis.pagehelper.domain.PageRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * @author yuemingwu@hand-china.com
 */
@Service
public class SoLineServiceImpl implements SoLineService {
	@Autowired
	private SoLineMapper lineMapper;
	@Autowired
	private SoLineRepository soLineRepository;
	@Autowired
	private SoHeaderRepository soHeaderRepository;


	@Override
	@Transactional(rollbackFor = Exception.class)
	public void deleteBySoLineIds(List<Long> soLineIds, Long soHeaderId) {
		List<HodrSoLine> soLines = new ArrayList<>();
		for (Long soLineId : soLineIds) {
			HodrSoLine exist = soLineRepository.selectByPrimaryKey(soLineId);
			if (exist == null) {
				throw new CommonException("htdo.warn.soLine.notFound");
			}
			HodrSoHeader soHeaderCheck = soHeaderRepository.selectByPrimaryKey(soHeaderId);
			System.out.println(soHeaderCheck.toString());
			if (!"NEW".equals(soHeaderCheck.getOrderStatus()) && !"REJECTED".equals(soHeaderCheck.getOrderStatus())) {
				throw new CommonException("htdo.warn.soHeader.wrongStatus");
			}
			soLines.add(exist);
		}
		soLineRepository.batchDelete(soLines);
	}

	@Override
	public List<HodrSoLine> selectBySoHeaderId(Long soHeaderId) {
		return lineMapper.selectBySoHeaderId(soHeaderId);
	}

	@Override
	public Page<HodrSoLine> pageSelectBySoHeaderId(Long soHeaderId, PageRequest pageRequest) {
		return PageHelper.doPage(pageRequest, () -> lineMapper.selectBySoHeaderId(soHeaderId));
	}
}
